<template>
  <div :class="{'mobile-create': showMobilePage}" class="create-customer">
    <Title :title="title" style="margin-bottom:16px;"/>
    <el-form ref="editCustomerForm" :model="editCustomerForm" :rules="editCustomerRules" :label-position="formAlign" class="lineHeight32" label-width="110px">
      <el-row type="flex" class="response-el-row">
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="客户名称" prop="clientName" class="client-name">
            <el-input :disabled="canEdit" v-model.trim="editCustomerForm.clientName" :maxlength="50" name="clientName" type="text"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="客户类型" prop="clientType" class="client-name">
            <el-select v-model="editCustomerForm.clientType" size="small" placeholder="请选择">
              <el-option
                v-for="item in clientTypeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="创建人" prop="createName" class="client-name">
            <el-input
              v-model.trim="editCustomerForm.createName"
              :disabled="true"
              :maxlength="50"
              name="createName"
              type="text"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="标签" prop="tag">
            <TagSelect v-model="editCustomerForm.tag" :collapse-tags="false" :module-type="TAG_MODULES.MENGLI_CUSTOMER" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="备注" prop="remark">
            <el-input v-model.trim="editCustomerForm.remark" :maxlength="200" class="client-textarea" name="remark" type="textarea" resize="none"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="所属部门" prop="department">
            <el-cascader
              v-select-scroll
              v-model="editCustomerForm.department"
              :show-all-levels="false"
              :options="deptTreeList"
              :props="{
                emitPath:false,
                value: 'id',
                label: 'name',
                checkStrictly: true,
                multiple: true,
              }"
              class="multiple-select-scroll"
              placeholder="请选择所属部门"
              size="small"
              filterable
              clearable>
              <template slot-scope="{ data }">
                <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                  <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                  <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                </el-tooltip>
                <span v-else>{{ data.name }}</span>
              </template>
            </el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <Title :title="'开票信息'" style="margin:8px 0 16px 0;"/>
    <el-form :model="editCustomerForm" :label-position="formAlign" class="lineHeight32" label-width="110px">
      <el-row type="flex" class="response-el-row">
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="纳税人识别号" class="client-name">
            <el-input v-model.trim="editCustomerForm.invoiceInfo.taxpayerNum" :maxlength="50" type="text"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="开户行" class="client-name">
            <el-input v-model.trim="editCustomerForm.invoiceInfo.openBank" :maxlength="50" type="text"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="开户账号" class="client-name">
            <el-input v-model.trim="editCustomerForm.invoiceInfo.accountNum" :maxlength="50" type="text"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="注册电话">
            <el-input v-model.trim="editCustomerForm.invoiceInfo.phone" :maxlength="50" type="text"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="开票地址">
            <el-input v-model.trim="editCustomerForm.invoiceInfo.invoiceAddress" :maxlength="50" type="text"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="一般纳税人证明">
            <upAttachment
              ref="uploadAttachment"
              :hide-confirm="true"
              :file-list="editCustomerForm.invoiceInfo.taxpayerAttachment"
              import-api="/common/file/upload"
              btn-text="上传文件"
              @complateSetData="completeSetData($event, 'taxpayerAttachment')"
              @removeFileList="removeFileList($event, 'taxpayerAttachment')" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <Title :title="'联系人'" style="margin:8px 0 16px 0"/>
    <ContactTable ref="contactTable" v-model="contactObj" :dept-tree-list="deptTreeList" :order-private-id ="orderPrivateId" del-auth-str="mengli:customer:deleteContact" @orderPrivateIdChange="orderPrivateIdChange" @delContact="delContact"/>
    <fixed-pagination>
      <div class="center">
        <el-button :loading="loading" type="primary" size="small" @click="toSave('editCustomerForm')">保存</el-button>
        <el-button type="info" size="small" class="cancel-btn-style" @click="toBack">取消</el-button>
      </div>
    </fixed-pagination>
  </div>
</template>
<script>
import Title from '@/components/Title';
import { editMengliCustomer, createMengliCustomer, getMengliCustomerInfo } from '@/api/mengli';
import { mapState } from 'vuex';
import TagSelect from '@/components/Common/tagSelect';
import upAttachment from '@/components/Common/upAttachment/index';
import ContactTable from '@/views/customer/module/contactTable';
import { hasRouteAuth } from '@/utils/permission';
import { TAG_MODULES } from '@/utils/const';
import { getDepartmentAll } from '@/api/config';
import mobileCreate from '@/mixins/mobileCreate';

export default {
  components: { Title, TagSelect, upAttachment, ContactTable },
  mixins: [mobileCreate],
  data() {
    return {
      TAG_MODULES,
      successRoute: 'mengliCustomer',
      editCustomerForm: {
        clientName: '',
        createName: '',
        remark: '',
        clientType: null,
        tag: [],
        invoiceInfo: {
          taxpayerNum: '',
          openBank: '',
          accountNum: '',
          phone: '',
          invoiceAddress: '',
          taxpayerAttachment: []
        },
        department: []
      },
      editCustomerRules: {
        clientName: [{ required: true, trigger: 'blur', message: '请填写客户名称' }],
        clientType: [{ required: true, trigger: 'change', message: '请选择客户类型' }],
        department: [{ required: true, trigger: 'change', message: '请选择所属部门' }]
      },
      title: '新增客户',
      customerId: '',
      loading: false,
      clientTypeOption: [
        { value: 1, label: '个人' },
        { value: 0, label: '公司' }
      ],
      contactObj: [], // 联系人列表数据
      contactLoading: false,
      orderPrivateId: 1,
      deptTreeList: [],
      delContactData: [] // 被删除的联系人数据
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    canEdit() {
      return !!(this.customerId && !this.hasRouteAuth('mengli:customer:editClientName'));
    }
  },
  created() {
    this.customerId = Number(this.$route.params.customerId) || '';
    if (this.$route.params.routeName) {
      this.successRoute = this.$route.params.routeName;
    }
    if (!this.customerId) {
      const { userInfo: { userName }} = this;
      this.editCustomerForm.createName = userName;
      if (this.userInfo.deptName && this.userInfo.deptName.length > 0) {
        let temp = this.userInfo.deptName.filter(item => {
          return item.name === '萌力星球';
        });
        temp = temp.length > 0 ? temp : this.userInfo.deptName;
        this.editCustomerForm.department.push(temp[0].id);
      }
    } else {
      this.title = '编辑客户';
      this.getInfo();
    }
    this.queryDeptTreeList();
  },
  methods: {
    hasRouteAuth,
    getInfo() {
      getMengliCustomerInfo(this.customerId).then(res => {
        this.editCustomerForm = res.data;
        this.editCustomerForm.department = this.editCustomerForm.department ? this.editCustomerForm.department.map(item => {
          return item.id;
        }) : [];
        res.data.contactObj.map(item => {
          item.department = this.formatTag(item.department);
          item.associateList = item.associate;
          if (item.associate && item.associate.length > 0) item.associate = item.associate.map(i => { return i.id; });
          if (item.coDepartment && item.coDepartment.length > 0) item.coDepartment = item.coDepartment.map(i => { return i.id; });
          item.orderPrivateId = this.orderPrivateId++;
        });
        this.contactObj = res.data.contactObj;
        this.$refs['contactTable'].setFirstSelectTag();
      }).catch(err => {
        console.error(err);
      });
    },
    orderPrivateIdChange(num) {
      if (!num) return;
      this.orderPrivateId = num;
    },
    // 获取所属部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      });
    },
    delContact(val) {
      this.delContactData.push(val);
    },
    formatTag(val) {
      if (val && val instanceof Array) {
        return val.map(item => {
          return item.name;
        }).join(',');
      } else {
        return '--';
      }
    },
    add(params) {
      createMengliCustomer(params).then(({ code, message }) => {
        this.loading = false;
        this.$message.success('添加成功');
        if (this.successRoute === 'mengliCustomer') {
          this.$router.push({
            name: 'mengliCustomer'
          });
        } else {
          this.$router.push({
            name: this.successRoute,
            params: { customerId: this.customerId }
          });
        }
      }, result => {
        this.loading = false;

        // this.$message.error(result.message);
      });
    },
    edit(params) {
      editMengliCustomer(params).then(({ code, message }) => {
        this.loading = false;
        this.$message.success('修改成功');
        if (this.successRoute === 'customer') {
          this.$router.push({
            name: 'mengliCustomer'
          });
        } else {
          this.$router.push({
            name: this.successRoute,
            params: { customerId: this.customerId }
          });
        }
      }, result => {
        this.loading = false;
        // this.$message.error(result.message);
      });
    },
    toSubmit() {
      const contactObj = [];
      let contactData = JSON.parse(JSON.stringify(this.contactObj));
      contactData = contactData.concat(this.delContactData);
      if (contactData.length) {
        contactData.forEach(el => {
          const item = {
            associate: el.associate,
            coDepartment: el.coDepartment,
            contactPerson: el.contactPerson.trim(),
            tel: el.tel,
            deleted: el.deleted ? el.deleted : 0
          };
          if (this.customerId) {
            item.id = el.id;
          }
          contactObj.push(item);
        });
      }
      const params = {
        ...this.editCustomerForm,
        contactObj
      };
      if (!this.customerId) {
        this.loading = true;
        this.add(params);
      } else {
        this.loading = true;
        this.edit(params);
      }
    },
    toSave(formValue) {
      try {
        const editCustomerForm = this.$refs[formValue];
        const params = [];
        params.push(this.$refs.contactTable.validate());
        params.push(this.getFormPromise(editCustomerForm));
        Promise.all(params).then(res => {
          const validateResult = res.every(item => !!item);
          if (validateResult) {
            this.toSubmit();
          } else {
            return false;
          }
        });
      } catch (error) {
        console.log(error);
      }
    },
    getFormPromise(form) {
      return new Promise(resolve => {
        form.validate(res => {
          resolve(res);
        });
      });
    },
    querySearch(queryString, cb) {
      cb(this.clientGradeList);
    },
    toBack() {
      if (this.successRoute === 'customer') {
        this.$router.push({
          name: 'mengliCustomer'
        });
      } else {
        this.$router.push({
          name: this.successRoute,
          params: { customerId: this.customerId }
        });
      }
    },
    completeSetData({ data, fileName }, key) {
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (this.editCustomerForm.invoiceInfo[key]) {
        this.editCustomerForm.invoiceInfo[key].push(fileList);
      } else {
        this.$set(this.editCustomerForm.invoiceInfo, key, [fileList]);
      }
      key === 'certificateFile' && this.$refs['applicationInfoForm'].validateField(key);
    },
    removeFileList({ file, index }, key) {
      this.editCustomerForm.invoiceInfo[key].splice(index, 1);
      key === 'certificateFile' && this.$refs['applicationInfoForm'].validateField(key);
    }
  }
};
</script>
<style  lang="scss" scoped>
.create-customer {
  margin: 16px;
  background-color: #fff;
  padding: 24px 24px 50px 24px;
  min-height: calc(100vh - 70px);
  &::v-deep {
    .el-form {
      .el-input {
        width: 240px;
      }
      .el-select {
        height: 30px;
        .el-input {
          height: 30px;
          line-height: 30px;
          width: 240px;
        }
      }
      .el-form-item {
        margin-bottom: 24px;
        /* .el-form-item__label {
          font-size: 13px !important;
          // line-height: 16px !important;
        } */
        .el-input__icon {
          line-height: 24px;
        }
        input {
          height: 30px;
          width: 240px;
          line-height: 16px;
        }
      }
      .contact-list {
        margin-bottom: 16px;
        &:last-child {
          margin-bottom: 0;
        }
      }
      .add-btn {
        button {
          width: 501px;
          background-color: #f4f4f4;
          border: 1px dashed #e0e0e0;
          color: #777;
          .add-img {
            margin-right: 8px;
          }
        }
      }
      .crm-add-btn {
        .el-form-item__content {
          margin-left: 0 !important;
        }
      }
    }
  }
  .client-textarea {
    width: 240px;
  }
}
.mobile-create {
  .client-textarea {
    width: 100%;
  }
}
</style>
